package work.parabola.keyboardswitch.service.impl;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import work.parabola.keyboardswitch.common.ResponseCode;
import work.parabola.keyboardswitch.common.RoleEnum;
import work.parabola.keyboardswitch.common.ServerResponse;
import work.parabola.keyboardswitch.common.UserConst;
import work.parabola.keyboardswitch.dao.LoginUserDoMapper;
import work.parabola.keyboardswitch.pojo.UserSession;
import work.parabola.keyboardswitch.pojo.query.LoginQuery;
import work.parabola.keyboardswitch.pojo.repository.LoginUserDo;
import work.parabola.keyboardswitch.service.IUserService;

import javax.servlet.http.HttpSession;

@Service
public class UserServiceImpl implements IUserService {

    @Autowired
    private LoginUserDoMapper loginUserDoMapper;

    @Override
    public ServerResponse login(HttpSession session, LoginQuery loginQuery) {
        if (loginQuery == null) {
            return ServerResponse.createByErrorCodeMessage(ResponseCode.ILLEGAL_ARGUMENT.getCode(), ResponseCode.ILLEGAL_ARGUMENT.getDesc());
        }
        ServerResponse response = loginQuery.validate();
        if (!response.isSuccess()) {
            return response;
        }
        LoginUserDo loginUserDo = this.loginUserDoMapper.selectByNamePassword(loginQuery.getUsername(),
                loginQuery.getPassword());
        if (loginUserDo == null) {
            return ServerResponse.createByErrorMessage("用户名或者密码错误");
        }
        UserSession userSession = new UserSession();
        userSession.setId(loginUserDo.getId());
        userSession.setName(loginUserDo.getName());
        userSession.setRoleType(loginUserDo.getRoleType());
        userSession.setRoleName(RoleEnum.codeOf(loginUserDo.getRoleType()).getValue());
        session.setAttribute(UserConst.CURRENT_USER, userSession);
        return ServerResponse.createBySuccessMessage("登录成功");
    }
}
